from flask import render_template, g, redirect, request, jsonify, current_app

from info import db, constants
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue


@user_blue.route('/news_list')
@user_login_data
def news_list():
    # 获取页数
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)


@user_blue.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    """用户发布新闻"""
    if request.method == "GET":

        categories = []
        # 获取所有分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        # 定义列表保存分类数据
        categories_dicts = []
        for category in categories:
            categories_dicts.append(category.to_dict())
        # 移除最新
        categories_dicts.pop(0)
        # 返回
        return render_template("news/user_news_release.html", data={"categories": categories_dicts})
    #
    # 1. 获取要提交的数据
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 1.2 尝试读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 将标题图片上传到七牛
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 初始化新闻模型，并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@user_blue.route("/collection")
@user_login_data
def user_collection():
    """用户新闻收藏"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 对用户收藏的新闻进行分页返回,默认返回第一页
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for collection in collections:
        collection_dict_li.append(collection.to_basic_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": collection_dict_li

    }
    return render_template("news/user_collection.html", data=data)


@user_blue.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    """修改密码"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if request.method == "GET":
        # 获取数据
        return render_template("news/user_pass_info.html")
    # post请求
    # 1.获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2.判断旧密码是否正确
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    # 3.设置新密码
    user.password = new_password
    return jsonify(errno=RET.OK, errmsg="修改密码成功")


@user_blue.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    """用户头像"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})
    else:
        # 修改头像
        try:
            avatar = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")
        if not avatar:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 2. 将文件上传到七牛云
        try:
            url = storage(avatar)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传文件错误")
        # 3. 将头像信息更新到用户模型中
        user.avatar_url = url
        # 4. 保存到数据库
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")
        # 返回上传结果
        return jsonify(errno=RET.OK, errmsg="上传OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@user_blue.route("/base_info", methods=["POST", "GET"])
@user_login_data
def base_info():
    """用户基本资料"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user": user.to_dict()})
    # post请求
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 更新保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    return jsonify(errno=RET.OK, errmsg="OK")


@user_blue.route("/info")
@user_login_data
def get_user_info():
    """
    获取用户信息
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    data = {"user": user.to_dict()}
    return render_template("news/user.html", data=data)
